'use strict';
const {
	log
} = require('console');
// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const {
	Buffer
} = require('buffer');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});

exports.main = async (event, context) => {
	const db = uniCloud.database();
	const _ = db.command;
	//event为客户端上传的参数
	console.log('http支付回调 : ', event)
	let parms = JSON.parse(event.body) //获取报文主体
	console.log('获取报文主体', parms);

	let parmsmsg = JSON.parse(parms.msg)
	console.log('获取报文主体msg的值', parmsmsg);

	let coupon_id = parmsmsg.coupon_id
	let app_id = parmsmsg.app_id
	let tt_openid = parmsmsg.open_id

	// 查询token
	let restoken = await vk.baseDao.select({
		dbName: "a_appid", // 表名
		whereJson: { // 条件
			appid: app_id
		},
	});
	console.log("res2", restoken.rows[0].appsecret);
	let token = restoken.rows[0].appsecret;
	let publicKey = restoken.rows[0].publicKey;
	let beanyhq = restoken.rows[0].beanyhq


	function verify(httpBody, publicKey, signStr, timestamp, nonce) {
		const buffer = Buffer.from(`${timestamp}\n${nonce}\n${httpBody}\n`, 'utf-8');
		const message = buffer.toString();
		crypto.getHashes(); // 这行代码会列出所有支持的哈希算法
		const verifier = crypto.createVerify('RSA-SHA256');
		verifier.update(message);

		const publicKeyObject = stringToPublicKey(publicKey);
		const signatureBuffer = Buffer.from(signStr, 'base64');

		return verifier.verify(publicKeyObject, signatureBuffer);
	}

	function stringToPublicKey(publicKey) {
		// const decoded = Buffer.from(publicKey, 'base64');
		// return crypto.createPublicKey(decoded);
		// 移除不必要的换行符和空格
		const cleanedKey = publicKey.replace(/\s/g, '');
		// 添加 PEM 头和尾
		const pemFormattedKey = `-----BEGIN PUBLIC KEY-----\n${cleanedKey}\n-----END PUBLIC KEY-----`;
		// 创建 PublicKey 对象
		return crypto.createPublicKey(pemFormattedKey);
	}


	// 假设以下是您收到的数据
	const timestamp = event.headers['byte-timestamp'];
	const nonce = event.headers['byte-nonce-str'];
	const httpBody = event.body;
	const signStr = event.headers['byte-signature'];

	const result = verify(httpBody, publicKey, signStr, timestamp, nonce);


	// 如果签名失败， 则直接返回
	if (!result) {
		console.log("签名校验失败");
		let res = {
			"err_no": 0,
			"err_tips": "fail"
		}
		return res
	}


	//如果算出来的签名和签名一致，说明请求来源正常，进行以下操作


	let nowtime = new Date().getTime()
	console.log("nowtime===", nowtime);
	const userInfo = await db.collection('uni-id-users').where({
		tt_openid: tt_openid,
		appid: app_id
	}).get()
	console.log("userInfo=============", userInfo);

	const order_tempmm = await db.collection('a_jindou_detail').where({
		coupon_id: coupon_id,
	}).get()


	if (order_tempmm.data.length == 0) {
		//给用户加上400金豆
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				tt_openid: tt_openid,
				appid: app_id
			},
			dataJson: {
				balance: _.inc(beanyhq),
			}
		});
		console.log("newInfo", newInfo);


		// //添加金豆收支明细
		const add_jindou = await db.collection('a_jindou_detail').add({
			coupon_id: coupon_id,
			user_id: userInfo.data[0]._id,
			nickname: userInfo.data[0].nickname || "匿名",
			change_num: beanyhq, //增加的金豆数量
			change_reason: "通过复访领取" + beanyhq + "看剧金豆",
			appid: userInfo.data[0].appid || "0",
			appname: userInfo.data[0].appname || "0",
			tfid: userInfo.data[0].tfid || "0", //投放链接的系统_ID
			ad_id: userInfo.data[0].ad_id || "0",
			middleman_id: userInfo.data[0].middleman_id || "0", //隶属机构
			invite_code: userInfo.data[0].invite_code || "0",
			type: "income", //类型：expend:支出,income:收入。
			_add_time: nowtime,
		})


		//金豆到账后实现核销动作
		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: app_id, // id
				client_secret: token, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})


		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token
		console.log("access_token", access_token);
		let hxdh = vk.pubfn.createOrderNo("hx")
		console.log("开发者核销单号", hxdh);
		// 核销券
		let urlT = "https://open.douyin.com/api/promotion/v1/coupon/batch_consume_coupon"
		let responseText = await uniCloud.httpclient.request(urlT, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
				"access-token": access_token,
			},
			data: {
				"open_id": tt_openid,
				"consume_out_no": hxdh,
				"app_id": app_id,
				"coupon_id_list": [
					coupon_id
				],
				"consume_time": Math.floor(nowtime / 1000)
			},
			dataType: 'text', // 指定返回值为json格式，自动进行parseK
		})
		//coupon_receive_list  coupon_receive_list
		console.log("看看核销状态", responseText);
		let qhxjl = JSON.parse(responseText.data)
		if (qhxjl.err_no == 0) {
			console.log("核销已成功");
			// 查询券模板

		}



	}

	let res = {
		"err_no": 0,
		"err_msg": "",
		"notify_status": "success" // success 平台不会重试通知请求, fail 平台会重试通知请求
	}
	console.log("res", res);

	return res
};